<?php
/**
 * @author yuanyitian
 * @date 2024/10/21 3:28
 */

namespace api\admin;

class qrcode
{

    /**
     * @author yuanyitian
     * @date 2024/10/21 3:25
     */


    /**
     * 获取小程序码
     */
    public function gerWechatQrcodeUrl(array $shop_info, string $path, string $params): string
    {
        $page = $path;
        $scene = $params;
        $shop_id = (int)$shop_info['shop_id'];

        $app = (new getWxConfig())->getMiniProgramApp($shop_info);
        $data = [
            'page' => $page,//跳转的小程序绝对路径
            //'scene' => $scene,//跳转携带的参数值（key=value&key=value）
            'env_version' => 'release'//正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版
        ];
        $response=$app->app_code->getUnlimit($scene,$data);
        $url = '';
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs('runtime/logs/code_temp', time() . '.png');
            $upload = new Qiniu();
            $path = $shop_id.'/code_temp';
            $export_name = 'runtime/logs/code_temp/'.$filename;
            $uploadPath = $export_name;
            $res = $upload->upload($uploadPath,$path ,'png');
            if($res){
                //   unlink($export_name);
                $url = $upload->getFileName();
            }

        }



        $url="https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN";

        $res = $this->http($url, "json", "POST", $data);//请求小程序码官方接口


        $ext = "png";
        $name = mt_rand('10000', '99999');
        $file = $this->binary_get($name, $res, $ext);//二进制转码存缓存
        $uploadPath = date('Y-m-d') . '/' . $shop_id . 'wechat_qrcode';
        $res = $upload->upload($file["path"], $uploadPath, $ext);//上传图片
        if (!$res) {
            return '';
        } else {
            return $upload->getFileName();//获取图片地址
        }
    }

    /**
     * @author yuanyitian
     * @data 2023/12/29 16:03
     * 二进制内容写入临时缓存
     */
    public static function binary_get($name, $file, $ext)
    {
        $path = tempnam(sys_get_temp_dir(), "qrcode_" . $name . time());
        $handle = fopen($path, "w+");
        fwrite($handle, $file);
        fclose($handle);
        $res = [];
        $res["name"] = $name . time() . "." . $ext;
        $res["path"] = $path;
        return $res;

    }



    //获取微信access_token
    public function getAccessToken(){
        $url="https://api.weixin.qq.com/cgi-bin/token";
        $data=[
            'grant_type'=>'client_credential',
            'appid'=>$GLOBALS['wechat_appid'],
            'secret'=>$GLOBALS['wechat_secret']
        ];
        $res=http($url,'json','GET',$data);
        return out_right($res);
    }

}